<?php
class XtagModel extends Model {
	protected	$tableName	=	'x_tag';
	protected	$fields		=	array (0 =>'tagid',1 =>'tagname',2 =>'tf',3 =>'idf',4 =>'stf',5 =>'weight','_autoinc' => true,'_pk' => 'tagid');

	//添加标签
	public function addTag($tagname) {
		//过滤列表值
		$map['tagname']	=	t($tagname);

		//查找Tag
		$cate	=	$this->where($map)->find();
		if($cate){
			$this->setField('count',$cate['count']+1,'tagid='.$cate['id']);
			
			return $cate['tagid'];
		//自动添加
		}else{
			return $this->add($map);
		}
	}

	//获取标签ID
	public function getTagId($tagname) {
		
		//解析输入
		if(is_array($tagname)){
			$tagnames	=	$tagname;
			$returnType	=	'array';
		}else{
			$tagname	=	str_replace(array(' ','，',';','；'),',',$tagname);
			$tagnames	=	explode(',',$tagname);
			$returnType	=	'string';
		}

		//获取TagId
		foreach($tagnames	as $k=>$v){
			$tags[$k]	=	$this->addTag($v);
		}

		if($returnType == 'array'){
			return $tags;
		}else if($returnType == 'string'){
			return implode(',',$tags);
		}
	}

	//获取标签名称
	public function getTagName($tagid) {
		
		//解析输入
		if(is_array($tagid)){
			$tagids		=	$tagid;
			$returnType	=	'array';
		}else{
			$tagid		=	str_replace(array(' ','，',';','；'),',',$tagid);
			$tagids		=	explode(',',$tagid);
			$returnType	=	'string';
		}
		
		$map['tagid']	=	array('in',$tagids);
		$cate	=	$this->where($map)->findAll();

		if($cate){
			//重组输出结果,以tagid为key，tagname为value
			foreach($cate as $v){
				$cateids[$v['tagid']]	=	$v['tagname'];
			}
			//按输入顺序格式化输出
			foreach($tagids as $k=>$v){
				$tags[$k]	=	$cateids[$v];
			}

			if($returnType == 'array'){
				return $tags;
			}else if($returnType == 'string'){
				return implode(',',$tags);
			}

		}else{
			return false;
		}
	}

	//格式化输入
	public function formatTags($tagname) {
		$tagname	=	str_replace(array(' ','，',';','；'),',',$tagname);
		return trim($tagname,',');
	}

	//输入多个
	protected function _parse_input($input) {
		if(is_numeric($input)){
			return array(intval($input));
		}else if(is_string($input)){
			$inputs	=	explode(',',$input);
			//array_map();
		}else if(is_array($input) || is_object($input)){

			return $input;
		}else{
			return false;		
		}
	}

	//过滤key,允许格式 数字字母下划线，list:key 不允许出现html代码 和这些符号 ' " & * % ^ $ ? ->
	protected function _strip_key($key=''){

		$key	=	strip_tags($key);
		$key	=	str_replace(array('\'','"','&','*','%','^','$','?','->'),'',$key);

		return $key;
	}		
}
?>